package com.dayuanit.dy16.atm.controller;

import com.dayuanit.dy16.atm.dto.ResponseDTO;
import com.dayuanit.dy16.atm.entity.User;
import com.dayuanit.dy16.atm.entity.WxBind;
import com.dayuanit.dy16.atm.service.IUserService;
import com.dayuanit.dy16.atm.util.AccessTokenDomain;
import com.dayuanit.dy16.atm.util.WxUserInfoDomain;
import com.dayuanit.dy16.atm.wx.WxHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class WxController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private WxHandler wxHandler;

    /**
     * 第一步 获取code
     * @return
     */
    @RequestMapping("/wx/loginUrl")
    @ResponseBody
    public ResponseDTO wxLoginUrl() {
        return ResponseDTO.success(wxHandler.codeRequestUrl());
    }

    /**
     * 获取accessToken
     * @param code
     */
    @RequestMapping(value = "/wx/wxCallBack")
    public String wxCallBack(String code, HttpServletRequest request) {
        System.out.println("wx login call back... code=" + code);

        AccessTokenDomain accessTokenDomain = wxHandler.getAccessToken(code);

        // 检查是否绑定过
        WxBind wxBind = userService.getWxBind(accessTokenDomain.getOpenid());
        if (null != wxBind) {
            // 如果已经绑定 则直接登录
            User user = userService.getUser(wxBind.getUserId());
            httpSession.setAttribute(user_login_flag, user);
            return "redirect:/user/toHome.do";
        }

        WxUserInfoDomain wxUserInfo = wxHandler.getUserInfo(accessTokenDomain);
        httpSession.setAttribute("wxUserInfo", wxUserInfo);

        return "redirect:/wx/toWxBind.do";
    }

    @RequestMapping("/wx/wxBind")
    @ResponseBody
    public ResponseDTO wxBind(String username, String password) {
        WxUserInfoDomain wxUserInfoDomain = (WxUserInfoDomain)httpSession.getAttribute("wxUserInfo");
        // 校验用户名和密码是否正确
        User user = userService.login(username, password);

        httpSession.setAttribute(user_login_flag, user);

        // 将微信账号和atm账号进行绑定
        userService.wxBind(wxUserInfoDomain.getOpenid(), wxUserInfoDomain.getNickname(), user);

        return ResponseDTO.success();
    }
}
